package com.lin.cms.service.impl;

import java.sql.Timestamp;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lin.cms.common.security.BadCredentialsException;
import com.lin.cms.common.security.UsernameNotFoundException;
import com.lin.cms.common.security.encoder.PwdEncoder;
import com.lin.cms.dao.UserMapper;
import com.lin.cms.domain.Config;
import com.lin.cms.domain.User;
import com.lin.cms.service.ConfigService;
import com.lin.cms.service.UserService;

@Service
public class UserServiceImpl implements UserService{

	public User selectByPrimaryKey(Integer userId) {
		// TODO Auto-generated method stub
		return userMapper.selectByPrimaryKey(userId);
	}

	
	public Integer errorRemaining(String username) {
		// TODO Auto-generated method stub
		if (StringUtils.isBlank(username)) {
			return null;
		}
		User user = getByUsername(username);
		if (user == null) {
			return null;
		}
		long now = System.currentTimeMillis();
		Config configLogin = configService.getConfigLogin();
		int maxErrorTimes = configLogin.getErrorTimes();
		int maxErrorInterval = configLogin.getErrorInterval() * 60 * 1000;
		Integer errorCount = user.getErrorCount();
		Date errorTime = user.getErrorTime();
		if (errorCount <= 0 || errorTime == null
				|| errorTime.getTime() + maxErrorInterval < now) {
			return maxErrorTimes;
		}
		return maxErrorTimes - errorCount;
	}
	public User getByUsername(String username) {
		return userMapper.getByUsername(username);
	}
	public User login(String username, String password, String ip)
			throws UsernameNotFoundException, BadCredentialsException {
		// TODO Auto-generated method stub
		User user = getByUsername(username);
		if (user == null) {
			throw new UsernameNotFoundException("username not found: "
					+ username);
		}
		if (!pwdEncoder.isPasswordValid(user.getPassword(), password)) {
			updateLoginError(user.getUserId(), ip);
			throw new BadCredentialsException("password invalid");
		}
		if (!user.getActivation()) {
			throw new BadCredentialsException("account not activated");
		}
		updateLoginSuccess(user.getUserId(), ip);
		return user;
	}
	
	public void updateLoginSuccess(Integer userId, String ip) {
		User user = selectByPrimaryKey(userId);
		Date now = new Timestamp(System.currentTimeMillis());

		user.setLoginCount(user.getLoginCount() + 1);
		user.setLastLoginIp(ip);
		user.setLastLoginTime(now);

		user.setErrorCount(0);
		user.setErrorTime(null);
		user.setErrorIp(null);
	}
	
	public void updateLoginError(Integer userId, String ip) {
		User user = selectByPrimaryKey(userId);
		Date now = new Timestamp(System.currentTimeMillis());
		Config configLogin = configService.getConfigLogin();
		int errorInterval = configLogin.getErrorInterval();
		Date errorTime = user.getErrorTime();

		user.setErrorIp(ip);
		if (errorTime == null
				|| errorTime.getTime() + errorInterval * 60 * 1000 < now
						.getTime()) {
			user.setErrorTime(now);
			user.setErrorCount(1);
		} else {
			user.setErrorCount(user.getErrorCount() + 1);
		}
	}
	
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private ConfigService configService;
	@Autowired
	private PwdEncoder pwdEncoder;
	
}
